//
//  AssetDetailViewController.swift
//  Exchange
//
//  Created by rui on 2018/5/4.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit

class AssetDetailViewController: BaseViewController, SelectmangerDelegate {
    private let kAssetDetailTableViewCell = "AssetDetailTableViewCell"
    
    var viewModel:AssetDetailViewModel?
    
    lazy var assetNameLabel: UILabel = {
        let lbl = UILabel(frame: CGRect(x: 16, y: 0, width: self.view.width, height: 48))
        lbl.textColor = UIColor(hexStr: "#e7ebf4")
        lbl.font = UIFont.systemFont(ofSize: 23)
        return lbl
    }()
    
    lazy var assetNameView: UIView = {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: self.view.width, height: 48))
        view.backgroundColor = kTitleColor
        assetNameLabel.text = viewModel?.model.coinCode
        view.addSubview(assetNameLabel)
        return view
    }()
    
    lazy var tableView: UITableView = {
        let rect = CGRect(x: 0, y: assetNameLabel.bottom, width: self.view.width, height: self.view.height - assetNameLabel.height)
        let table = UITableView(frame: rect, style: .plain)
        table.autoresizingMask = [.flexibleWidth,.flexibleHeight]
        table.delegate = self
        table.dataSource = self
        table.themeBackground = ThemeManager.ThemeColorKeys.background2
        table.register(UINib(nibName: kAssetDetailTableViewCell, bundle: nil), forCellReuseIdentifier: kAssetDetailTableViewCell)
        table.tableFooterView = UIView()
        table.themeSeparatorColor = ThemeManager.ThemeColorKeys.separator
        table.mj_header = EoeRefreshHeader(refreshingTarget: self, refreshingAction: #selector(loadData(compant:)))
        table.mj_footer = EoeRefreshFooter(refreshingTarget: self, refreshingAction: #selector(loadData(compant:)))
        table.allowsSelection = false
        return table
    }()
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        self.viewModel = AssetDetailViewModel()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //注册监听
        self.viewModel?.addObserver(self, forKeyPath: "refreshBool", options: [.new,.old], context: nil)
        self.viewModel?.archiveInformation()
        
        initUI()
    }
    
    func initUI() {
        self.title = kText("资金明细")
        self.view.addSubview(assetNameView)
        self.view.addSubview(tableView)
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: kText("筛选"), style: .plain, target: self, action: #selector(filter))
        tableView.creatEmptyView()
    }
    
    @objc func filter() {
        dPrint("筛选")
        if viewModel?.type == .coinType {
            SelectActionManger.manager.creatSheet(style: .capitalAllStyle, selectStr: viewModel?.currentType, dataSource: self)
        }else {
        SelectActionManger.manager.creatSheet(style: .capitalStyle, selectStr: viewModel?.currentType, dataSource: self)
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.convention()
    }
    
    //Mark -- SelectmangerDelegate
    func selectModel(model: SheetModel) {
        viewModel?.currentType = model.selectStr!
        viewModel?.pageNo = 1
        self.viewModel?.archiveInformation()
    }
    
  
    @objc override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "refreshBool" {
            tableView.reloadData()
            self.endRefresh()
        }
        
    }
    
    @objc func loadData(compant:UIView) {
        
        if compant.isEqual(tableView.mj_header) {
            viewModel?.pageNo = 1
            viewModel?.archiveInformation()
            
        }else if compant.isEqual(tableView.mj_footer){
            viewModel?.pageNo = (viewModel?.pageNo)! + 1
            viewModel?.archiveInformation()
        }
        
    }
    func endRefresh() {
        self.endRefresh(table: tableView)
        
    }
    func endRefresh(table:UITableView) {
        table.mj_footer?.endRefreshing()
        table.mj_header?.endRefreshing()
        if table.isEqual(tableView) {
            if (viewModel?.dataArr.count)! % 10 != 0 && (viewModel?.dataArr.count)! < 10{
                table.mj_footer?.endRefreshingWithNoMoreData()
            }else {
                table.mj_footer?.endRefreshing()
            }
            table.mj_footer?.isHidden = viewModel?.dataArr.count != 0 ? false : true
        }
    }
    deinit {
        self.viewModel?.removeObserver(self, forKeyPath: "refreshBool", context: nil)
    }
}


extension AssetDetailViewController: UITableViewDelegate,UITableViewDataSource {
    
    // MARK: - UITableViewDelegate UITableViewDataSource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return (self.viewModel?.dataArr.count)!
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: kAssetDetailTableViewCell, for: indexPath) as! AssetDetailTableViewCell
        let model = viewModel?.dataArr[indexPath.row]
        if model != nil {
            cell.setModel(model: model!, type: (viewModel?.type)!)
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 115
    }
    
    

}
